package com.ubtrobot.serialportlib.serial;

import android.os.SystemClock;
import android.util.Log;



import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

/**
 * Description
 *
 * @author jianlin.duan
 * 2020/11/11, Create file
 */
public class SerialReader implements Runnable{

    private static final String TAG = "SerialReader";

    private final InputStream mInputStream;
    private final SerialDataListener mReceiver;
    private boolean mIsInterrupted = false;

    public SerialReader(InputStream inputStream, SerialDataListener receiver){
        mInputStream = inputStream;
        mReceiver = receiver;
    }

    @Override
    public void run() {
        InputStream is = mInputStream;
        int available;
        int first;
        try {
            while (!mIsInterrupted
                    && is != null
                    && (first = is.read()) != -1) {
                do {
                    available = is.available();
                    SystemClock.sleep(5);
                } while (available != is.available());
                available = is.available();
                byte[] bytes = new byte[available + 1];
                is.read(bytes, 1, available);
                bytes[0] = (byte) (first & 0xFF);

                Log.e(TAG, "读取到的byte数组：" + Arrays.toString(bytes));
                report(bytes);
            }
        } catch (IOException e) {
                e.printStackTrace();
                return;
        }
    }

    private void report(final byte[] data) {
        HiExecutor.INSTANCE.execute(()->{
            //String temp = ConvertUtils.bytes2HexString(data);
            String temp = byte2HexStr(data);
            Log.e(TAG, "读取到的byte数组转化后：" + temp);
            mReceiver.onDataReceived(temp);
        });
    }


    /**
     * bytes转换成十六进制字符串
     *
     * @param b byte数组
     * @return String 每个Byte值之间空格分隔
     */
    public String byte2HexStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
			sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }
}
